#!/bin/bash
###
 # @FilePath: deploy2.sh
 # @@author: wjj
 # @Date: 2025-10-24 18:53:24
 # @@Description: new js file
### 

# 部署脚本 - 包含前端构建和nginx配置更新 (不需要sudo权限)
set -e  # 遇到错误立即退出

echo "🚀 开始部署流程..."
echo "📦 重新安装依赖..."
pnpm install --no-frozen-lockfile
echo "🔨 构建前端项目..."
npm run build:staging

# 步骤3: 验证nginx配置语法
echo "🔍 验证nginx配置语法..."
if nginx -t 2>/dev/null; then
    echo "   ✅ nginx配置语法正确"
else
    echo "   ❌ nginx配置语法错误，请检查 fastbot.conf"
    echo "   可以运行: nginx -t 查看详细错误信息"
    exit 1
fi

# 步骤4: 重新加载nginx配置
echo "🔄 重新加载nginx配置..."
if nginx -s reload 2>/dev/null; then
    echo "   ✅ nginx配置重新加载成功"
else
    echo "   ❌ nginx重新加载失败，可能需要手动重启nginx"
    echo "   请手动执行: sudo nginx -s reload"
fi

# 步骤5: 清理潜在的nginx缓存
echo "🧹 清理nginx缓存（如果有）..."
# 一些常见的nginx缓存目录
CACHE_DIRS="/tmp/nginx /var/cache/nginx /usr/local/var/cache/nginx"
for dir in $CACHE_DIRS; do
    if [ -d "$dir" ]; then
        echo "   🗑️  清理缓存目录: $dir"
        rm -rf "$dir"/* 2>/dev/null || true
    fi
done
echo "转移图标"
cp -rf /Users/litmatchqa/huakaiyingmo/tools/favicon.ico /Users/litmatchqa/.jenkins/workspace/测试平台-web/dist
# 步骤5: 验证部署
echo "🔍 验证部署状态..."
echo "   - 检查dist目录: $(ls -la dist/ | head -5)"
echo "   - 检查config.ini: $(test -f dist/config.ini && echo '✅ 存在' || echo '❌ 缺失')"
echo "   - nginx配置路径: $(pwd)/fastbot.conf"

echo ""
echo "🎉 部署完成！"
echo "📋 部署摘要:"
echo "   - npm依赖: 已重新安装"
echo "   - 前端构建: 已完成 $(date '+%Y-%m-%d %H:%M:%S')"
echo "   - nginx配置: 已验证并重载"
echo "   - nginx缓存: 已清理"
echo "   - 配置文件: $(test -f dist/config.ini && echo '已就绪' || echo '需要检查')"
echo ""
echo "🌐 访问地址: https://fastbot.ksztone.com"

echo ""
echo "🚨 重要: 如果页面仍显示旧版本，请按以下步骤清理缓存:"
echo "   1️⃣  浏览器强刷: Ctrl+F5 (Windows) 或 Cmd+Shift+R (Mac)"
echo "   2️⃣  清除浏览器缓存: F12 → Network → 勾选 'Disable cache'"
echo "   3️⃣  隐私模式测试: 打开隐私/无痕浏览窗口访问"
echo "   4️⃣  如仍有问题，等待5-10分钟让CDN缓存过期"

echo ""
echo "🔧 调试命令:"
echo "   - 检查nginx日志: tail -f /usr/local/var/log/nginx/fastbot.error.log"
echo "   - 手动重启nginx: sudo nginx -s reload"
echo "   - 验证文件时间戳: ls -la dist/"
echo "   - 检查文件hash: ls -la dist/js/ dist/css/"

# 提示nginx配置信息
echo ""
echo "💡 nginx配置:"
echo "   - 配置文件位置: $(pwd)/fastbot.conf"
echo "   - 确保nginx主配置包含: include $(pwd)/fastbot.conf;"
echo "   - HTML文件: 不缓存"
echo "   - JS/CSS文件: 智能缓存（有hash=长期，无hash=短期）" 